package org.kth.dks.test_bed;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.kth.dks.dks_comm.ConnectionManager;
import org.kth.dks.dks_comm.DKSOverlayAddress;
import org.kth.dks.dks_dht.DKSDHTImpl;

/**
 * <p>Title: DKS Hello World Application</p>
 * <p>Description: DKS Middleware</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: KTH-IMIT/SICS</p>
 * @author Ali Ghodsi
 * @version 1.0
 */

public class Server {

  /**
   * Local port number DKS will run on
   */
  private long START_PORT = 4441;

  /**
   * Logical DKS identifier to be used for the first node
   */
  private long START_IDENTIFIER = 0;

  public static void main(String[] args) {
    System.out.println("Starting DKS");

    Server helloApp = new Server();

    helloApp.run(args);
  }

  /**
   * Creates two DKS nodes, adds a hello world string through one node and retrieves it from the other
   */
  void run(String[] args) {

    if (args.length<2) {
      System.err.println("Syntax:\nServer PORTNUMBER IDENTIFIER\n");
      System.exit(0);
    }

    START_PORT = Integer.parseInt(args[0]);
    START_IDENTIFIER = Integer.parseInt(args[1]);

    ConnectionManager cm = null;
    DKSDHTImpl firstNode = null;

    try {
      cm = ConnectionManager.getInstance( (int) START_PORT); // Static factory only used for testing, should use getInstance (singleton)
//      cm = ConnectionManager.getInstanceMultiHome((int)START_PORT, InetAddress.getByName("213.89.66.28")); 
      // Static factory only used for testing, should use getInstance (singleton)
      // The following will start a DKS node running on START_PORT with identifier 0
      // The two last parameters are 0 and null respectively always for the first node in the system

      // Format of DKSOverlayAddresses : dksoverlay://[GroupId]/[NodeId]/[NodeGUID] (NodeId's must be unique)
      DKSOverlayAddress firstNodeId = new DKSOverlayAddress("dksoverlay://0/" +
          START_IDENTIFIER + "/0");
      firstNode = new DKSDHTImpl(cm, firstNodeId);

      firstNode.create();

      System.out.println("First node created with DKSURL " +
                         firstNode.getDKSURL());

    }
    catch (Exception ex) {
      ex.printStackTrace();
    }

    System.out.println("Hit enter to exit: ");

    BufferedReader cin = new BufferedReader( new InputStreamReader(System.in) );

    try {

    cin.read();

    }
    catch (Exception ex) {
      ex.printStackTrace();
    }

    sleep(500);
    firstNode.leave(); // causes the node to gracefully leave

    sleep(500);

    cm.end(); // Closes down all the sockets and threads
    System.out.println("Exiting.");

  }

  /**
   * Sleeps for some milliseconds
   * @param msec is the number of milliseconds
   */

  static void sleep(long msec) {
    try {
      Thread.sleep(msec);
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

}
